<template>
    <div class="page-container">
        <div class="loading" v-if="loading">
            <loading></loading>
        </div>
        <div class="page"></div>
    </div>
</template>

<script>
import Loading from "@/components/loading";
import { postMessageRemote } from "@/settings";
export default {
    name: "APP",
    data() {
        return {
            previewSrc: "",
            loading: true, // 加载状态
        };
    },
    watch: {
        loading: async function (val) {
            if (!val) {
                if (!document.querySelector("#frame")) {
                    const iframeSrc = localStorage.getItem("iframe");
                    const container = this.$el.querySelector(".page");
                    const frame = document.createElement("iframe");
                    frame.id = "frame";
                    frame.width = "100%";
                    frame.height = "100%";
                    frame.src = iframeSrc || postMessageRemote;
                    container.appendChild(frame);
                    frame.addEventListener("load", async () => {
                        this.loading = false;

                        if (frame.children.length == 0) {
                            console.log("error");
                        }
                        const bookmarkMap = await this.syncChromeBookmark();
                        // 加载并发送书签数据
                        frame.contentWindow.postMessage(
                            {
                                action: "toggleBookmark",
                                data: bookmarkMap,
                            },
                            "*"
                        );
                    });
                }
            }
        },
    },
    created() {},
    components: {
        Loading: Loading,
    },
    mounted() {
        this.loading = false;
        // 监听并执行操作
        window.addEventListener("message", async (e) => {
            const origin = e.origin;
            if (!origin == postMessageRemote) {
                return;
            }
            // 约定通过action定义行为
            if (!e.data.action) return;
            const splitIndex = e.data.action.indexOf(":");
            // 约定通过:作为分隔, 前半部分作为命令体, 后半部分作为唯一标识
            const action =
                splitIndex == -1
                    ? e.data.action
                    : e.data.action.substring(0, splitIndex);
            // 通用命令执行
            if (e.data.common) {
                const { payload } = e.data;
                const { module, func, param } = payload;
                const result = await this.$chromeService[module][func].apply(
                    this.$chromeService[module],
                    param
                );
                this.$logger.debug(`${e.origin}请求: ${e.data.action}`);
                const res = {
                    action: e.data.action,
                    data: result,
                };
                document
                    .querySelector("#frame")
                    .contentWindow.postMessage(res, "*");
                this.$logger.debug(`平台响应: ${res}`);
                return;
            }
            switch (action) {
                case "openWidget": {
                    const url = e.data.payload.param[0];
                    window.open(url, "_self");
                    break;
                }
            }
        });
    },
    methods: {
        // 读取图片, 返回base64
        readImage(url, cb) {
            this.$chromeService.Favicon.loadFaviconByUrl(url)
                .then((base64) => {
                    cb(base64);
                })
                .catch((e) => {
                    console.log(e);
                });
        },
        // 同步书签，历史记录等数据
        syncChromeBookmark() {
            return new Promise((resolve, reject) => {
                this.$chromeService.Bookmark.getBookmarks(true)
                    .then((result) => {
                        resolve(result);
                    })
                    .catch((e) => {
                        resolve(undefined);
                    });
            });
        },
    },
};
</script>
<style scoped lang="less">
.page-container {
    box-sizing: border-box;
    height: 100vh;
    width: 100vw;
    overflow-x: hidden;
    position: relative;
    .loading {
        position: absolute;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background: #eee;
        color: #333;
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden;
    }
    .page {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
}
</style>
